var	db;

function check_notes() {
	console.log("check notes");
	var xhr = new XMLHttpRequest();
	xhr.open("GET", "http://www.epitech.eu/intra/index.php?section=etudiant&page=notes&action=index_act", true);
	xhr.send();
	xhr.onreadystatechange = function() {
		if (xhr.readyState === 4) {
			r = new RegExp("<table>(.*?)</table>", "i");
			r1 = new RegExp("<tr>(.*?)</tr>", "gis");
			r2 = new RegExp("<td.*?>(.*?)</td>", "gi");
			r3 = new RegExp("<a href=\".*?\">(.*?)</a>.*?<td.*?align='right'>(\\d*)</td>", "gi");
			res = xhr.responseText;
			res = res.replace(/[\n]/gi,"").replace(/>[\s*?]</gm, "");
			res = r.exec(res)[1];
		
			db.transaction(function(tx) {
				tx.executeSql("SELECT * FROM notes", [], function(tx, result){
					console.log("apres select\n Nombre de note : "+result.rows.length);
					//console.log(regix2.exec(res));
					var nbNew = 0;
					/*
					* pownd le undefined qui traine
					*/
					while ((s = r1.exec(res))) {
						arr = new Array()
						while((u = r2.exec(s[1]))) {
							//console.log(u);
							arr.push(u[1]);
						}
						//console.log(temp);
						//console.log("nbs result : "+result.rows.length);
						for (i=0; i < result.rows.length; i++) {
							//console.log(result.rows.item(i));
							if (result.rows.item != null && result.rows.item(i).titre == arr[2])
								break;
						}
						if (i == result.rows.length) {
							console.log("insert");
							/*
							* Date a mettre en timestamp
							* Valeur a caster
							*/
							tx.executeSql("INSERT INTO notes (date, module, titre, note, moy, comm) VALUES (?, ?, ?, ?, ?, ?)", 
								[arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]]);
							nbNew++;
						}
					}
					
					console.log("new: "+nbNew);
					if (nbNew > 0) {
						chrome.browserAction.setBadgeText({text:nbNew.toString(10)});
						localStorage.setItem("notif", "note|"+arr[2]+"|"+arr[3]);
					}
					console.log("fin while");
				});
			});
		}
	};
}

function createTable() {
	db.transaction(function(tx) {
		tx.executeSql("CREATE TABLE notes (date, module, titre, note, moy, comm)");
	});
}

function init() {
	db = openDatabase("EpiDash", "1.0", "", 200000);
    if (!localStorage.first_run) {
		//init defaut params
		localStorage.first_run = true;
		createTable();
		//openOptions();
	}
	window.setInterval(check_notes, 3600000);
	//check_notes();
}
